package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.CheckGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryPageBean.getQueryString());
        log.debug("CheckGroupService__findByCondition:{" + page + "}");
        return new PageResult(page.getTotal(), page);
    }

    @Override
    @Transactional
    public void add(Integer[] checkitemIds, CheckGroup checkGroup) {
        checkGroupDao.add(checkGroup);
        setRelation(checkGroup.getId(), checkitemIds);
    }

    @Override
    public void deleteById(Integer id) {
        //校验与检查组是否有数据关联
        Long count = checkGroupDao.findCountById(id);
        if (count > 0) {
            log.debug("该检查组与套餐存在数据关联,无法删除!!!");
            throw new BusinessRuntimeException("该检查组与套餐存在数据关联,无法删除!!!");
        }
        checkGroupDao.deleteRelation(id);
        checkGroupDao.deleteById(id);
    }

    private void setRelation(Integer id, Integer[] checkitemIds) {
        if (id != null && checkitemIds != null && checkitemIds.length != 0) {
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.setRelation(id, checkitemId);
            }
        }
    }
}
